package com.davesandoval.tpdroid;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Main extends Activity {
	static String username = null;
	static String logid = null;
	private String passwd = null;
	public static String globalURI = "http://tp.nuwavepartners.com/mobile/PPC/";
	static Httpclient client;
	static SharedPreferences prefs;
	private ProgressBar pb1;
	private Handler handler;
	static TPdbAdapter dbHelper;
	protected static String[][] soList = {};
	protected static boolean loggedIn = false;
	int returnedResultCode = 0;
	private Runnable runnable;
	private Button btnViewSO;
	private Button btnLogin;
	private Button btnLogout;
	private Button btnUpdateDB;
	private Button btnPushLogs;
	private static Cursor allLogs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogout = (Button) findViewById(R.id.btnLogout);
		btnViewSO = (Button) findViewById(R.id.btnViewSO);
		btnPushLogs = (Button) findViewById(R.id.btnPushLogs);
		btnUpdateDB = (Button) findViewById(R.id.btnUpdateDB);
		pb1 = (ProgressBar) findViewById(R.id.progressBar1);
		handler = new Handler();

		dbHelper = new TPdbAdapter(this);
		dbHelper.open();
		dbHelper.close();

		SharedPreferences prefs = getSharedPreferences("USER_PREFS", 0);
		username = prefs.getString("username", "null");
		logid = prefs.getString("logid", "null");
		passwd = prefs.getString("passwd", "null");
		// globalURI = prefs.getString("globalURI", "null");

		Runnable initialClient = new Runnable() {
			public void run() {
				if (isOnline()) {
					client = new Httpclient(globalURI);
				}
			}
		};
		initialClient.run();
		pb1.setVisibility(View.INVISIBLE);

		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isOnline()) {
					if (loggedIn) {
						Toast.makeText(getBaseContext(),
								"You are already logged in!",
								Toast.LENGTH_SHORT).show();
					} else {
						if (logid != "null") {
							loggedIn = true;
							Toast.makeText(getBaseContext(),
									"Using saved credentials...",
									Toast.LENGTH_SHORT).show();
						} else {
							startActivityForResult((new Intent(Main.this,
									LoginActivity.class)), returnedResultCode);
						}
					}
				} else {
					Toast.makeText(
							getBaseContext(),
							"You have no Internet connection currently,\n"
									+ "you can only work in offline mode for now...",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		btnUpdateDB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!loggedIn) {
					Toast.makeText(
							getBaseContext(),
							"You are not logged in!\nPlease login using the login button.",
							Toast.LENGTH_SHORT).show();

				} else {
					try {
						client.doLogin(globalURI, logid, passwd);
						runnable = new Runnable() {
							public void run() {
								handler.post(new Runnable() {
									public void run() {
										pb1.setVisibility(View.VISIBLE);
										Toast.makeText(
												getBaseContext(),
												"Please wait while populating the database...",
												Toast.LENGTH_LONG).show();
									}
								});
								try {
									soList = client.checkOpen(globalURI);
									populateDB(soList);
								} catch (ClientProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								handler.post(new Runnable() {

									public void run() {
										pb1.setVisibility(View.GONE);
									}
								});
							}
						};
						new Thread(runnable).start();
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		btnViewSO.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Main.this, SoViewActivity.class));
			}
		});

		btnPushLogs.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isOnline()) {
					try {
						client.doLogin(globalURI, logid, passwd);
					} catch (ClientProtocolException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					if (dbHelper.isOpen()) {
					} else {
						dbHelper.open();
					}
					allLogs = dbHelper.fetchAllLogs();
					allLogs.moveToFirst();
					if (allLogs.getCount() == 0) {
						Toast.makeText(getBaseContext(),
								"There are no offline logs.", Toast.LENGTH_LONG)
								.show();
					} else {
						Runnable runnable = new Runnable() {
							public void run() {
								handler.post(new Runnable() {
									public void run() {
										pb1.setVisibility(View.VISIBLE);
										Toast.makeText(
												getBaseContext(),
												"Please wait while posting logs to the server...",
												Toast.LENGTH_SHORT).show();
										for (int l = 1; l < allLogs.getCount(); l++) {
											try {
												pushALog();
											} catch (ClientProtocolException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											} catch (IOException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
											allLogs.moveToNext();
										}
										Main.dbHelper.dropAllOfflineLogs();
										handler.post(new Runnable() {
											public void run() {
												pb1.setVisibility(View.GONE);
											}
										});
									}
								});
							}
						};
						new Thread(runnable).start();
					}
				} else {
					Toast.makeText(
							getBaseContext(),
							"You have no Internet connection currently,\n"
									+ "you can only work in offline mode for now...",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		btnLogout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (loggedIn) {
					try {
						client.logOut(globalURI);
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				dbHelper.close();
				loggedIn = false;
				finish();
			}
		});

	}// -----END ONCREATE-------------

	@Override
	public void onResume() {
		if (loggedIn && returnedResultCode == 1) {
			Runnable runnable = new Runnable() {
				public void run() {
					handler.post(new Runnable() {
						public void run() {
							pb1.setVisibility(View.VISIBLE);
							Toast.makeText(
									getBaseContext(),
									"Please wait while populating the database...",
									Toast.LENGTH_SHORT).show();
						}
					});
					try {
						soList = client.checkOpen(globalURI);
						populateDB(soList);
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.post(new Runnable() {
						public void run() {
							pb1.setVisibility(View.GONE);
						}
					});
				}
			};
			new Thread(runnable).start();
			returnedResultCode = 0;
		}
		super.onResume();
	}

	public void populateDB(String[][] so) throws ClientProtocolException,
			IOException {
		disableButtons();
		long result = 0;
		String[] currentSO = new String[so.length];
		dbHelper.open();
		dbHelper.cleanSO();
		String soTasks = client.getSOtasks();
		for (int i = 0; i < so.length; i++) {
			String[] soDetails = client.getSODetail(so[i][0]);
			if (dbHelper.soExists(so[i][0])) {
				// update the record
				String blnTask = "0";
				if (soTasks.contains(so[i][0])) {
					blnTask = "1";
				}
				result = dbHelper.updateSO(so[i][0], so[i][1], soDetails[0],
						so[i][4], so[i][2], so[i][3], so[i][5], soDetails[1],
						soDetails[2], blnTask, soDetails[4]);
			} else {
				String[] accountDetails = client.getAccountDetail(soDetails[2],
						so[i][1]);
				currentSO[i] = so[i][0];
				String blnTask = "0";
				if (soTasks.contains(so[i][0])) {
					blnTask = "1";
				}
				result = dbHelper.addSO(so[i][0], so[i][1], soDetails[0],
						so[i][4], so[i][2], so[i][3], so[i][5], soDetails[1],
						soDetails[2], blnTask, soDetails[4]);
				if (dbHelper.accountExists(accountDetails[4])) {
					// don't add the account
				} else {
					result = dbHelper.addAccount(accountDetails[0],
							accountDetails[1], accountDetails[2],
							accountDetails[3], soDetails[2]);
				}
			}
		}
		enableButtons();
	}// ------End populateDB-----------

	@Override
	public void onBackPressed() {
		dbHelper.close();
		if (loggedIn) {
			try {
				client.logOut(globalURI);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		finish();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		returnedResultCode = resultCode;
	}

	@Override
	protected void onPause() {
		// if (runnable.)
		System.out.println("----------Main onPause----------");
		super.onPause();
	}

	@Override
	protected void onStop() {
		System.out.println("----------Main onStop----------");
		dbHelper.close();
		if (loggedIn) {
			try {
				client.logOut(globalURI);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		super.onStop();
	}

	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return true;
		}
		return false;
	}

	private void disableButtons(){
		btnViewSO.setClickable(false);
		btnLogin.setClickable(false);
		btnLogout.setClickable(false);
		btnUpdateDB.setClickable(false);
		btnPushLogs.setClickable(false);
	}
	
	private void enableButtons(){
		btnViewSO.setClickable(true);
		btnLogin.setClickable(true);
		btnLogout.setClickable(true);
		btnUpdateDB.setClickable(true);
		btnPushLogs.setClickable(true);
	}
	
	private void pushALog() throws ClientProtocolException, IOException {
		String soNumber = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_SO_NUM));
		String newStatus = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_NEW_STATUS));
		String soReason = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_SO_REASON));
		String logComment = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_LOG_DETAIL));
		String startDate = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_START_DATE));
		String endDate = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_END_DATE));
		String startTime = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_START_TIME));
		String endTime = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_END_TIME));
		String workRequested = "";
		String workPerformed = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_LOG_DETAIL));
		String chargeable = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_CHARGEABLE));
		String billable = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_BILLABLE));
		String copylc = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_COPY_LC));
		String blntask = allLogs.getString(allLogs
				.getColumnIndex(TPdbAdapter.KEY_BLN_TASK));

		Cursor soCursor = Main.dbHelper.fetchSOViaSONum(soNumber);
		String accountNum = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_ACCOUNT_NUMBER));
		String strRateBasis = soCursor.getString(soCursor
				.getColumnIndex(TPdbAdapter.KEY_STRRATEBASIS));

		client.putBatchSO(soNumber, newStatus, soReason, logComment, startDate,
				endDate, startTime, endTime, workRequested, workPerformed,
				chargeable, billable, copylc, blntask, accountNum, strRateBasis);
		Main.dbHelper.dropOfflineLogs(soNumber);
	}
}// -----END MAIN----------------------